package microgame.toolset.database;

import Core.Log4j2;
import Core.WebSocketServer;
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

public class DatabaseControl {
    private static DatabaseControl _instance;

    private MongoDatabase database;

    public static DatabaseControl Instance() {
        if (_instance == null) {
            _instance = new DatabaseControl();
        }

        return _instance;
    }

    public void Init() {
        try {
            File file = new File(WebSocketServer.class.getProtectionDomain().getCodeSource().getLocation().toURI());
            String absolutePath = file.getAbsolutePath();
            String folderPath;
            if (absolutePath.contains(".")) {
                folderPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
            }
            else {
                folderPath = absolutePath;
            }
            String xmlFile = folderPath + File.separator + "databaseConfig.xml";

            File f = new File(xmlFile);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(f);
            NodeList nl = doc.getElementsByTagName("config");
            if (nl.getLength() < 1) {
                Log4j2.LOGGER.error("databaseConfig.xml format error，it must have a config root.");
                return;
            }

            String host = "";
            int port = 0;
            for (int i = 0; i < nl.getLength(); i++) {
                host = doc.getElementsByTagName("host").item(i).getFirstChild().getNodeValue();
                port = Integer.parseInt(doc.getElementsByTagName("port").item(i).getFirstChild().getNodeValue());
            }

            MongoClient mongo = new MongoClient(host , port);
            database = mongo.getDatabase("GameAirPlane");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public MongoDatabase getDatabase() {
        return database;
    }
}
